package client.comm.baoding

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Bundle
import android.os.Process
import android.provider.Settings
import android.util.Log
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.databinding.ViewDataBinding
import client.comm.baoding.dialog.AgainEnterPrivacyDialog
import client.comm.baoding.dialog.MsgTitleDialog
import client.comm.baoding.dialog.UpDateDialog
import client.comm.baoding.fragment.ProtocolDialogFragment
import client.comm.baoding.ui.LoginActivity
import client.comm.baoding.ui.MainActivity
import client.comm.baoding.ui.vm.LauncherViewModel
import client.comm.baoding.utils.HandlerTip
import client.comm.baoding.utils.PreferencesManager
import client.comm.commlib.ContextProvider
import client.comm.commlib.toast.toast
import client.comm.commlib.utils.SharedUtil
import pub.devrel.easypermissions.AfterPermissionGranted
import pub.devrel.easypermissions.AppSettingsDialog
import pub.devrel.easypermissions.EasyPermissions


class LauncherActivity : BaseMiddleActivity<LauncherViewModel, ViewDataBinding>() {

    internal val RC_SMS = 0x88

    fun handle() {
        if (!SharedUtil.read("token", "").isNullOrEmpty()) {
//            val userState = SharedUtil.read("userState", -1)
//            if (userState == 1) {
            val intent =
                Intent(this@LauncherActivity, MainActivity::class.java)
            startActivity(intent)
//            } else if (userState == 0) {
//                val intent =
//                    Intent(this@LauncherActivity, UpGradeActivity::class.java)
//                startActivity(intent)
//            } else {
//                val intent =
//                    Intent(this@LauncherActivity, LoginActivity::class.java)
//                startActivity(intent)
//            }

        } else {
            val intent =
                Intent(this@LauncherActivity, LoginActivity::class.java)
            startActivity(intent)
        }
        finish()
    }

    override fun initData() {
//        requestExternalStorage()
//        startActivity(Intent(this, TestActivity::class.java))
        runHasPermis()
    }


    override fun observerUI() {
        viewModel.versionRet.observe(this, {
            it?.apply {
                if (it.isSuccess) {
                    data?.let {
                        if (it.state == 1) {//有新版本
                            ContextProvider.get().activity?.apply {
                                UpDateDialog(this, viewModel, it.url).apply {
                                    errorFun = {
                                        toast("下载失败，请重新下载")
                                        show()
                                    }
                                }.show()
                            }
                        } else if (it.state == 2) {
                            toast("系统维护")
                            Process.killProcess(0)
                        } else {
                            handle()
                        }
                    }
                } else {

                    MsgTitleDialog(this@LauncherActivity).apply {
                        title = "获取版本失败，请重新获取"
                        okTxt = "重新获取"
                        cancleTxt = "退出"
                        cancle = {
                            finish()
                        }
                        setCancelable(false)
                        setCanceledOnTouchOutside(false)
                        ok = {
                            viewModel.getVersion()
                        }
                    }.show()
                }
            }
        })

    }

    fun runHasPermis() {
        if (BuildConfig.DEBUG) {
            handle()
        } else
            viewModel.getVersion()
    }


    fun requestExternalStorage() {
        if (ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            ) == PackageManager.PERMISSION_GRANTED
        ) {//有權限
            runHasPermis()
        } else {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                0x99
            )
        }
    }

    fun showReDialog() {
        MsgTitleDialog(this).apply {
            title = "需要开启权限"
            okTxt = "去开启"
            cancleTxt = "退出"
            cancle = {
                finish()
            }
            setCancelable(false)
            setCanceledOnTouchOutside(false)
            ok = {
                val intent: Intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
                val uri = Uri.fromParts("package", packageName, null)
                intent.data = uri
                startActivityForResult(intent, 0x55)
            }

        }.show()

    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        if (ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            ) == PackageManager.PERMISSION_GRANTED
        ) {//有權限
            runHasPermis()
        } else {
            showReDialog()
        }
    }


    override fun getLayout(): Int {
        return R.layout.activity_launcher
    }

    override fun initViewModel(): LauncherViewModel = createViewModel()

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (ContextCompat.checkSelfPermission(
                this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE
            ) == PackageManager.PERMISSION_GRANTED
        ) {//有權限
            runHasPermis()
        } else {
            showReDialog()
        }
    }

}